import { getSpaces } from '@/api/space'

const state = {
    spaces: [],
    options: [],
}

const mutations = {
    SET_SPACES: (state, data) => {
        state.spaces = data
    },
    SET_OPTIONS: (state, data) => {
        state.options = data
    },
}

const buildTree = (data) => {
    let result = [];
    if (!Array.isArray(data)) {
        return result;
    }
    data.forEach((item) => {
        delete item.children;
    });
    let map = {};
    data.forEach((item) => {
        map[item.spaceID] = {
            value: item.spaceID,
            label: item.name
        }
    });
    data.forEach((item) => {
        let parent = map[item.parentID]
        if (parent) {
            (parent.children || (parent.children = [])).push(map[item.spaceID]);
        } else {
            result.push(map[item.spaceID])
        }
    });
    return result;
}

const actions = {
    GetSpaces: ({ commit }, params) => {
        new Promise((resolve, reject) => {
            getSpaces(params).then(res => {
                const { data } = res
                commit('SET_SPACES', data)
                commit('SET_OPTIONS', buildTree(data))
                resolve(data)
            }).catch(err => {
                reject(err)
            })
        })
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}